package xml;

import javax.xml.bind.annotation.adapters.XmlAdapter;

import cuShapes.Box;
import cuShapes.Ellipse;
import cuShapes.ShapeList;
import cuShapes.PQShape;

import java.util.LinkedList;

/**
 * Switches between a java ready {@link cuShapes.ShapeList ShapeList}, and a {@link xml.ShapeListType ShapeListType} object needed to write to xml.
 * @author mylesc,varunr
 *
 */
public class ShapeCollectionAdapter extends XmlAdapter<ShapeListType, ShapeList> {
	
	/**
	 * Marshals a java list of {@link cuShapes.PQShape PQShapes} into a ShapeListType object which is capable of being saved in xml.
	 * @param shapes a ShapeList object to be converted into xml saveable format.
	 * @return ShapeListType an object containing all of the data from shapes ready to be saved to xml.
	 */
	public ShapeListType marshal(ShapeList shapes) throws Exception {
		LinkedList<Box> boxes = new LinkedList<Box>();
		LinkedList<Ellipse> ellipses = new LinkedList<Ellipse>();

		for (PQShape e : shapes) {
			if (e instanceof Box){
				boxes.add((Box) e);
			} else if (e instanceof Ellipse) {
				ellipses.add((Ellipse) e);
			}
		}
		return new ShapeListType(boxes, ellipses);
	}

	/**
	 * Unmarshals the ShapeListType form of the PQShapes and creates a new java list of PQShapes.
	 * @param shapeList an object to fill a ShapeList with data that was saved in an xml file.
	 * @return shapes a ShapeList object that gets its data from shapeList.
	 */
	public ShapeList unmarshal(ShapeListType shapeList) throws Exception { 
		ShapeList shapes = new ShapeList();
		for(PQShape x : shapeList.getBoxes()) {
			shapes.add((Box) x);
		}
		for(PQShape x : shapeList.getEllipses()) {
			shapes.add((Ellipse) x);
		}
        
        return shapes;
	}
}
